﻿namespace CabinetGrid.DeviceDriver.IModules.Impls;

public class RFIDHFReaderModule : IModule
{
    private readonly ILogger _logger;
    private readonly ViewModel _viewModel;

    public RFIDHFReaderModule( ILoggerFactory loggerFactory, ViewModel viewModel )
    {
        _logger = loggerFactory.CreateLogger( "高频读写器模块" );
        _viewModel = viewModel;
    }

    public async Task StartAsync( CancellationToken cancellationToken )
    {
        if ( _viewModel.AppConfig.RFIDReaderCategory != "hf" ) return;

        try
        {
            _viewModel.AppConfig.RFIDReaderList.ForEach( config =>
            {
                if ( config.Enable is false ) return;

                var api = new Dev.Integration.HFReader.ApiClientBuilder( )
                                                      .UseReaderKind( config.Kind )
                                                      .UseReaderConfig( o =>
                                                      {
                                                          o.Connect.ConnectType = config.ConnectType;
                                                          o.Connect.ConnectArgs = config.ConnectArgs;
                                                          o.MonitorLogAction = ( level, log ) =>
                                                          {
                                                              switch ( level )
                                                              {
#if DEBUG
                                                                  case Dev.Integration.HFReader.Constants.LogLevel.Debug:
                                                                      {
                                                                          ConsoleWirter.Debug( $"+ [hf] {log}" );
                                                                          break;
                                                                      }
#endif
                                                                  case Dev.Integration.HFReader.Constants.LogLevel.Info:
                                                                      {
                                                                          _logger.Info( log );
                                                                          break;
                                                                      }
                                                                  case Dev.Integration.HFReader.Constants.LogLevel.Warn:
                                                                      {
                                                                          _logger.Warning( log );
                                                                          break;
                                                                      }
                                                                  case Dev.Integration.HFReader.Constants.LogLevel.Error:
                                                                      {
                                                                          _logger.Error( log );
                                                                          break;
                                                                      }
                                                              }
                                                          };
                                                      } )
                                                      .Build( );

                api.OnOpenedHandler = ( s, e ) => ConsoleWirter.Success( $"+ [hf] OnOpenedHandler: {api.ReaderId}" );
                api.OnClosedHandler = ( s, e ) => ConsoleWirter.Warning( $"+ [hf] OnClosedHandler: {api.ReaderId}" );
                //api.OnInventoryScanHandler = ( s, e ) => _viewModel.AddOrUpdateRFIDHFTag( e.TagInfo );    // 无block数据

                _viewModel.RFIDHFReaderList.Add( api );
            } );

            _logger.Info( $"注册成功" );
        }
        catch ( Exception ex )
        {
            _logger.Error( $"注册失败: {ex.Message}" );
        }

        await Task.CompletedTask;

        // 重连机制
        _ = Task.Factory.StartNew( ( ) =>
        {
            while ( true )
            {
                _viewModel.RFIDHFReaderList.ForEach( api =>
                {
                    try
                    {
                        if ( api.ReaderState == Dev.Integration.HFReader.Constants.ReaderState.Close )
                        {
                            api.Open( );
                        }
                    }
                    catch ( Exception ex )
                    {
                        ConsoleWirter.Warning( $"+ [hf] {api.ReaderConfig.Connect.ConnectArgs} 连接失败: {ex.Message}" );
                    }
                    finally
                    {
                        Thread.Sleep( 1000 );
                    }
                } );

                Thread.Sleep( 10 * 1000 );
            }
        } );
    }

    public async Task StopAsync( CancellationToken cancellationToken )
    {
        if ( _viewModel.AppConfig.RFIDReaderCategory != "hf" ) return;

        try
        {
            _viewModel.RFIDHFReaderList.ForEach( api =>
            {
                api.Close( );
            } );

            _logger.Info( $"注销成功" );
        }
        catch ( Exception ex )
        {
            _logger.Error( $"注销失败: {ex.Message}" );
        }

        await Task.CompletedTask;
    }
}
